package com.yin.controller;


import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yin.entity.UserEntity;
import com.yin.jpa.UserJPA;

/**
*@author LSY
*Time: 2018年12月26日下午3:02:56
*
*
*/
@RestController
@RequestMapping("/user")
public class LoginController {

	@Autowired
	private UserJPA userJPA;
	
	@Autowired
	private MessageSource messageSource;
	
	@RequestMapping(value = "/login",method = RequestMethod.GET)
	public String login(@Valid UserEntity user, HttpServletRequest request, BindingResult resultInfo) {
		if(resultInfo.hasErrors()) {
			StringBuilder msg = new StringBuilder();
			List<FieldError> fieldErrors = resultInfo.getFieldErrors();
			Locale currentLocale = LocaleContextHolder.getLocale();
			for(FieldError field : fieldErrors) {
				String msgError = messageSource.getMessage(field, currentLocale);
				msg.append(field.getField() + ":" + msgError);
			}
			return msg.toString();
		}
		
		String result = "登录成功";
		boolean flag = true;

		UserEntity userEntity = userJPA.findByUsername(user.getUsername());
		  //用户不存在
        if(userEntity == null){
            flag = false;
            result = "用户不存在，登录失败";}
        //密码错误
        else if(!userEntity.getUsername().equals(user.getUsername())){
            flag = false;
            result = "用户密码不相符，登录失败";
        }
        //登录成功
        if(flag){
            //将用户写入session
            request.getSession().setAttribute("user",userEntity);
        }
        return result;
	}
}
